package com.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @Author: luobiao
 * @Date: 2024/9/23 14:39
 * @Description:
 */
@Configuration
@ComponentScan
@EnableTransactionManagement
public class AppConfig {

    /**
     * 定义一个数据源
     *   autoconfigure:
     *     exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
     *   datasource:
     *     type: com.alibaba.druid.pool.DruidDataSource
     *     driver-class-name: com.mysql.jdbc.Driver
     *     url: jdbc:mysql://localhost:3306/test?useSSL=false
     *     username: root
     *     password: lb320.com
     * @return
     */
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test?useSSL=false");
        dataSource.setUsername("root");
        dataSource.setPassword("lb320.com");
        return dataSource;
    }

    /**
     * 定义一个JdbcTemplate来执行sql
     * @param dataSource
     * @return
     */
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    /**
     * 定义一个管理器
     * @param dataSource
     * @return
     */
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
